﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Web.Models;
using System.Web.Routing;
using MShop.Core.DataAccess;
using MShop.Core.Domain;
using MShop.Core;

namespace MShop.Web.Controllers
{
    [Authorize]
    public class UserCenterController : ControllerBase
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        private readonly IAreaGroupDao _AreaGroupDao;

        private readonly IProductDao _ProductDao;
        private readonly ICommonDao<ShopUsers> _CommonDao;
        private readonly ICommonDao<ShopUsersCryptography> _CommonDao2;
        private readonly ITradeDao _TradeDao;
        private readonly IShopUsersFavDao _ShopUsersFavDao;
        private readonly ICommonDao<ShopUsersAddress> _ShopUsersAddressDao;
        private readonly IShopContext _ShopContext;
        public UserCenterController(ICommonDao<ShopUsers> commonDao, IShopContext shopContext, ITradeDao tradeDao,
            ICommonDao<ShopUsersCryptography> commonDao2, IAreaGroupDao areaGroupDao,
            ICommonDao<ShopUsersAddress> shopUsersAddressDao,IShopUsersFavDao shopUsersFavDao, IProductDao productDao)
        {
            _CommonDao = commonDao;
            _CommonDao2 = commonDao2;
            _ShopContext = shopContext;
            _TradeDao = tradeDao;
            _AreaGroupDao = areaGroupDao;
            _ShopUsersAddressDao = shopUsersAddressDao;
            _ShopUsersFavDao = shopUsersFavDao;
            _ProductDao = productDao;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            AppendMeta("用户中心");
            IQueryable<Trade> trades = _TradeDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId).OrderByDescending(x => x.Created);
            _TradeDao.DeleteInvalidTrade(_ShopContext.CurrentUser.UserId, new TimeSpan(0, 3, 0));
            _TradeDao.SaveChanges();

            ViewData["success"] = trades.Count(x => x.TradeStatus == (int)TradeStatus.交易成功);
            ViewData["totalsum"] = _ShopContext.CurrentUser.ShopUsers.ShopUsersCryptography.TotalFee;
            return View(trades);
        }

        public ActionResult Menu()
        {
            ShopUsers user = _ShopContext.CurrentUser.ShopUsers;
            return PartialView("usercenter/menu", user);
        }


        [Authorize]
        public ActionResult Personal()
        {
            AppendMeta("修改资料");
            MShop.Core.Domain.ShopUsers user = _CommonDao.FirstOrDefault(x => x.UserId == _ShopContext.CurrentUser.UserId);
            return View(user);
        }

        [Authorize]
        public ActionResult Address()
        {
            AppendMeta("我的收货地址");
            IQueryable<ShopUsersAddress> address = _ShopUsersAddressDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId);
            if (address.Count() > 0)
            {
                ViewData["address"] = address.ToList()[0];
            }
            return View(address);
        }

        [Authorize]
        public ActionResult CreateAddress(int? id)
        {
            if (id == null)
            {
                AppendMeta("创建我的收货地址");
                ShopUsersAddress address = new ShopUsersAddress();
                ViewData["address"] = _ShopUsersAddressDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId);
               
                ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null));
              

                return View(address);
            }
            else
            {
                AppendMeta("修改我的收货地址");
                ShopUsersAddress address =
                               _ShopUsersAddressDao.FirstOrDefault(x => x.UserId == _ShopContext.CurrentUser.UserId && x.Id == id.Value);
                ViewData["address"] = _ShopUsersAddressDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId);
                ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null),address.AreaId,address.AreaGroup);
                return View(address);
            }
        }


        [Authorize]
        [HttpPost]
        public ActionResult CreateAddress(int? id, ShopUsersAddress address, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    AppendMeta("创建我的收货地址");
                    address.UserId = _ShopContext.CurrentUser.UserId;
                    _ShopUsersAddressDao.Save(address);
                    _ShopUsersAddressDao.SaveChanges();
                    return RedirectToAction("address");
                }
                else
                {
                    AppendMeta("修改我的收货地址");
                    ShopUsersAddress dbaddress =
                                   _ShopUsersAddressDao.FirstOrDefault(x => x.UserId == _ShopContext.CurrentUser.UserId && x.Id == id.Value);


                    UpdateModel<ShopUsersAddress>(dbaddress, new string[] { "Mobile", "Tel", "AreaId", "ReceiverName", "IsDefault", "Postcode", "Location", "Memo" });
                    if (address.IsDefault == true)
                    {
                        var q = from item in _ShopUsersAddressDao.GetAll() where item.UserId == _ShopContext.CurrentUser.UserId && item.Id != dbaddress.Id select item;
                        q.ToList().ForEach((x) =>
                        {
                            x.IsDefault = false;
                            _ShopUsersAddressDao.Update(x);
                        });
                    }
                    _ShopUsersAddressDao.SaveChanges(); 
                    return RedirectToAction("address");

                }
            }
            else
            {
                ViewData["area"] = new SelectedAreaGroupModel(_AreaGroupDao.Find(x => x.ParentId == null), address.AreaId, address.AreaGroup);
                ViewData["address"] = _ShopUsersAddressDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId);
                return View(address);
            }
        }

        [Authorize]
        public ActionResult DeleteAddress(int id)
        {
            AppendMeta("我的收货地址");
            ShopUsersAddress address = _ShopUsersAddressDao.FirstOrDefault(x => x.Id == id && x.UserId == _ShopContext.CurrentUser.UserId);
            if (address != null)
            {
                _ShopUsersAddressDao.Delete(address);
                _ShopUsersAddressDao.SaveChanges();
            }
            return RedirectToAction("address");
        }

        [Authorize]
        public ActionResult Point()
        {
            AppendMeta("我的积分");
            MShop.Core.Domain.ShopUsersCryptography user = _CommonDao2.Get(x => x.UserId == _ShopContext.CurrentUser.UserId);
            return View(user);
        }

        [Authorize]
        public ActionResult Balance()
        {
            AppendMeta("我的余额");
            MShop.Core.Domain.ShopUsersCryptography user = _CommonDao2.Get(x => x.UserId == _ShopContext.CurrentUser.UserId);
            return View(user);
        }

        [HttpPost]
        public ActionResult Personal(ShopUsers user, FormCollection collection)
        {
            AppendMeta("修改资料");
            return View(user);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            AppendMeta("修改密码");
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码无效或者新密码无效.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            AppendMeta("密码已修改");

            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        [Authorize]
        public ActionResult Buy()
        {
            AppendMeta("我购买过的商品");
            var q = _TradeDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId).ToList();
            List<int> list = new List<int>();
            foreach (var item in q)
            {
                if ((int)TradeStatus.交易成功 == item.TradeStatus)
                {
                    foreach (var subitem in item.Order)
                    {
                        if (subitem.ProductId.HasValue)
                        {
                            if (!list.Contains(subitem.ProductId.Value))
                            {
                                list.Add(subitem.ProductId.Value);
                            }
                        }
                    }
                }
            }

            var query = from item in _ProductDao.GetAll() where list.Contains(item.Id) select item;

            return View(query.OrderBy(x=>x.Sort));
        }


        [Authorize]
        public ActionResult Favorite()
        {
            AppendMeta("我的收藏");
            var q = _ShopUsersFavDao.Find(x => x.UserId == _ShopContext.CurrentUser.UserId).OrderByDescending(x => x.Id);
            return View(q);
        }

        [Authorize]
        public ActionResult FavItem(int id)
        {
            AppendMeta("我的收藏");
            var fav = _ShopUsersFavDao.FirstOrDefault(x => x.Id == id);
            switch (fav.FavType)
            {
                case "1":
                    break;
            }
            return RedirectToAction("item", "product", new { id = fav.FavId });
        }


        [Authorize]
        public ActionResult Promote()
        {
            AppendMeta("网站推广");
            MShop.Core.Domain.ShopUsersCryptography user = _CommonDao2.Get(x => x.UserId == _ShopContext.CurrentUser.UserId);
            return View(user);
        }
    }
}
